<?php

namespace common\models;

use Yii;
use common\extended\system\Util;

/**
 * This is the model class for table "bus_member".
 *
 * @property string $member_id
 * @property string $member_name
 * @property string $member_mobile
 * @property string $member_birthday
 * @property string $member_job
 * @property integer $member_sex
 * @property string $member_remark
 * @property string $constitution_remark
 * @property string $shop_id
 * @property integer $member_height
 * @property integer $member_weight
 * @property integer $member_breast
 * @property integer $member_waist
 * @property integer $member_hip
 * @property string $member_balance
 * @property string $member_give_balance
 * @property string $member_debt
 * @property string $last_consume_time
 * @property string $consume_count
 * @property string $consume_counts
 * @property integer $del_flag
 * @property string $create_time
 * @property string $boss_id
 */
class BusMember extends \yii\db\ActiveRecord
{
    /**
     * @var string 接收验证的错误信息
     */
    public $errorMessage = '';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'bus_member';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['member_name'], 'required'],
            [['member_birthday', 'last_consume_time', 'create_time', 'constitution_remark'], 'safe'],
            [['member_sex', 'shop_id', 'member_height', 'member_weight', 'member_breast', 'member_waist', 'member_hip', 'del_flag', 'boss_id', 'marriage', 'consume_counts'], 'integer'],
            ['member_sex', 'in', 'range' => [0, 1, 2]],
            [['member_balance', 'member_give_balance', 'member_debt', 'consume_count', 'member_type'], 'number'],
            [['member_name', 'member_remark', 'address'], 'string', 'max' => 255],
            [['member_mobile'], 'string', 'max' => 11],
            [['member_job'], 'string', 'max' => 45],
            ['member_mobile', 'checkMobile']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'member_id' => 'Member ID',
            'member_name' => '会员姓名',
            'member_mobile' => 'Member Mobile',
            'member_birthday' => 'Member Birthday',
            'member_job' => 'Member Job',
            'member_sex' => '会员性别',
            'member_remark' => 'Member Remark',
            'constitution_remark' => 'constitution_remark',
            'shop_id' => 'Shop ID',
            'member_height' => 'Member Height',
            'member_weight' => 'Member Weight',
            'member_breast' => 'Member Breast',
            'member_waist' => 'Member Waist',
            'member_hip' => 'Member Hip',
            'member_balance' => 'Member Balance',
            'member_give_balance' => 'Member Give Balance',
            'member_debt' => 'Member Debt',
            'last_consume_time' => 'Last Consume Time',
            'consume_count' => 'Consume Count',
            'consume_counts' => 'consume_counts',
            'del_flag' => 'Del Flag',
            'create_time' => 'Create Time',
            'boss_id' => 'Boss ID',
            'member_grade' => '会员等级'
        ];
    }

    public function checkMobile($attribute, $params)
    {
        if (!preg_match("/^1\d{10}$/", $this->member_mobile)) {
            $this->addError($attribute, '手机号码格式错误');
        }
    }

    /*模块交互接口  */
    /**
     * 记录会员消费记录
     * @date: 2016-2-22
     * @author: futao
     * @param integer $memberId  会员ID
     * @param array $data  写入的数据
     * @param $data['consume_amount']  会员消费总额
     * @param $data['consume_name']    会员消费的名称
     * @param $data['consume_type']    消费类型
     * @param $data['cash_pay']        现金消费（可为空）
     * @param $data['unionpay']        刷卡支付（可为空）
     * @param $data['balance_pay']     储值卡支付（可为空）
     * @param $data['give_pay']        赠送金额支付（可为空）
     * @param $data['debt_count']      欠款金额（可为空）
     * 备注：可见原型收银明细，需记录会员最后消费时间，需加上老板ID和分店ID
     * @return boolean
     */
    public function addMemberconsume($memberId, $data)
    {
        $BusMemberConsume = new BusMemberConsume();
        $BusMemberConsume->setAttributes($data);
        $BusMemberConsume->member_id = $memberId;
       // $BusMemberConsume->consume_time = date('Y-m-d H:i:s');

        if (empty($BusMemberConsume->boss_id)) {
            $this->errorMessage = '老板id不能为空';
            return false;
        }
        if (empty($BusMemberConsume->shop_id)) {
            $this->errorMessage = '分店id不能为空';
            return false;
        }
        if (empty($BusMemberConsume->consume_name)) {
            $this->errorMessage = '会员消费的名称不能为空';
            return false;
        }
        if (empty($BusMemberConsume->consume_type)) {
            $this->errorMessage = '消费类型不能为空';
            return false;
        }
        if (!is_numeric($BusMemberConsume->boss_id) || $BusMemberConsume->boss_id < 0) {
            $this->errorMessage = '老板id参数错误';
            return false;
        }
        if (!is_numeric($BusMemberConsume->shop_id) || $BusMemberConsume->shop_id < 0) {
            $this->errorMessage = '分店id参数错误';
            return false;
        }
        if (!is_numeric($BusMemberConsume->member_id) || $BusMemberConsume->member_id < 0) {
            $this->errorMessage = '会员id参数错误';
            return false;
        }
        if (!is_numeric($BusMemberConsume->consume_amount) || $BusMemberConsume->consume_amount < 0) {
            $this->errorMessage = '会员消费总额参数错误';
            return false;
        }
        $return = $BusMemberConsume->insert(false);
        if ($return) {
            return $BusMemberConsume->consume_id;
        }
        return false;
    }

    /**
     * 修改会员信息
     * @date: 2016-2-22
     * @author: futao
     * @param integer $memberId 会员ID
     * @param data['member_balance']      储值卡剩余金额
     * @param data['member_debt']         会员欠款金额
     * @param data['member_give_balance'] 赠送余额
     * @param data['member_name']         用户名
     * @param data['member_mobile']       电话
     * @param data['member_grade']        会员等级
     * 备注：$data都可为空
     * @return mixed
     */
    public function updateMemberinfo($memberId, $data)
    {

        if ($memberId < 1) {
            $this->errorMessage = '会员id错误';
            return false;
        }
        if ($data['member_mobile'] && !(preg_match("/^1\d{10}$/", $data['member_mobile']))) {
            $this->errorMessage = '手机号码格式不正确';
            return false;
        }
        if ($data['member_give_balance'] && $data['member_give_balance'] < 0) {
            $this->errorMessage = '赠送余额不能少于0';
            return false;
        }
        if ($data['member_debt'] && $data['member_debt'] < 0) {
            $this->errorMessage = '会员欠款金额不能少于0';
            return false;
        }
        return self::updateAll($data, ['member_id' => $memberId]);
    }

    /**
     * 添加会员
     * @date: 2016-2-22
     * @author: futao
     * @param array $data 添加会员所需的参数
     * @return boolean
     */
    public function addMember($data = [])
    {
        if ($data) {
            $this->setAttributes($data);
        }
        $this->create_time = date('Y-m-d H:i:s');

        if ($this->checkParams()) {
            return $this->insert(false);
        } else {
            return false;
        }
    }

    public function checkParams()
    {
        if (empty($this->member_name)) {
            $this->errorMessage = '姓名不能为空';
            return false;
        }
        if (Util::utf8_strlen($this->member_name) > 5) {
            $this->errorMessage = '姓名不能超过5个字符';
            return false;
        }
        if ($this->member_job && Util::utf8_strlen($this->member_job) > 7) {
            $this->errorMessage = '职业不能超过7个字符';
            return false;
        }
        if ($this->member_remark && Util::utf8_strlen($this->member_remark) > 500) {
            $this->errorMessage = '备注不能超过500个字符';
            return false;
        }
        if ($this->constitution_remark && Util::utf8_strlen($this->member_remark) > 200) {
            $this->errorMessage = '备注不能超过200个字符';
            return false;
        }
        if ($this->member_mobile && !(preg_match("/^1\d{10}$/", $this->member_mobile))) {
            $this->errorMessage = '手机号码格式不正确';
            return false;
        }
        if ($this->shop_id < 1) {
            $this->errorMessage = '所属分店id错误';
            return false;
        }
        if ($this->boss_id < 1) {
            $this->errorMessage = '老板id错误';
            return false;
        }
        if ($this->member_height && !is_numeric($this->member_height)) {
            $this->errorMessage = '身高必须是数字';
            return false;
        }
        if ($this->member_weight && !is_numeric($this->member_weight)) {
            $this->errorMessage = '体重必须是数字';
            return false;
        }
        if ($this->member_breast && !is_numeric($this->member_breast)) {
            $this->errorMessage = '胸围必须是数字';
            return false;
        }
        if ($this->member_waist && !is_numeric($this->member_waist)) {
            $this->errorMessage = '腰围必须是数字';
            return false;
        }

        return true;
    }

    /**
     * 增加会员欠款记录
     * @date: 2016-2-22
     * @author: futao
     * @param array $data 需要的参数数组
     * @return mixed
     */
    public function addMemberdebt($data)
    {
        $BusMemberDebt = new BusMemberDebt();
        $BusMemberDebt->setAttributes($data);
        $BusMemberDebt->debt_time = date('Y-m-d H:i:d');

        if (empty($BusMemberDebt->boss_id)) {
            $this->errorMessage = '老板id不能为空';
            return false;
        }
        if (empty($BusMemberDebt->shop_id)) {
            $this->errorMessage = '分店id不能为空';
            return false;
        }
        if (empty($BusMemberDebt->member_name)) {
            $this->errorMessage = '会员名不能为空';
            return false;
        }
        if (empty($BusMemberDebt->member_id)) {
            $this->errorMessage = '会员id不能为空';
            return false;
        }
        if (!is_numeric($BusMemberDebt->member_id) || $BusMemberDebt->member_id < 1) {
            $this->errorMessage = '会员id参数不合法';
            return false;
        }
		
        return $BusMemberDebt->insert(false);
    }

    /**
     * 添加会员拥有的卡项
     * @date: 2016-2-22
     * @author: futao
     * @param array $data 添加卡项的参数
     * @return mixed
     */
    public function addMemberbeautycard($data)
    {
        $BusMemberBeautycard = new BusMemberBeautycard();
        $BusMemberBeautycard->setAttributes($data);
        $BusMemberBeautycard->create_time = date('Y-m-d H:i:s');

        if (empty($BusMemberBeautycard->member_id)) {
            $this->errorMessage = '会员id不能为空';
            return false;
        }
        if (!is_numeric($BusMemberBeautycard->member_id) || $BusMemberBeautycard->member_id < 1) {
            $this->errorMessage = '会员id参数不合法';
            return false;
        }
        if (empty($BusMemberBeautycard->card_name)) {
            $this->errorMessage = '卡名称不能为空';
            return false;
        }
        if ($BusMemberBeautycard->total_times < $BusMemberBeautycard->remain_times) {
            $this->errorMessage = '使用次数不能大于总次数';
            return false;
        }
        if (empty($BusMemberBeautycard->boss_id)) {
            $this->errorMessage = '老板id不能为空';
            return false;
        }
        if (empty($BusMemberBeautycard->shop_id)) {
            $this->errorMessage = '分店id不能为空';
            return false;
        }

        return $BusMemberBeautycard->insert(false);
    }

    /**
     * 编辑会员卡项
     * @date: 2016-2-22
     * @author: futao
     * @param int $card_id 卡项id
     * @param int $shop_id 分店id
     * @param int $member_id 会员id
     * @param array $data 编辑卡项的参数
     * @return mixed
     */
    public function updateMemberbeautycard($card_id, $shop_id, $member_id, $data)
    {
        $BusMemberBeautycard = BusMemberBeautycard::findOne(['card_id' => $card_id, 'shop_id' => $shop_id, 'member_id' => $member_id]);
        unset($data['member_id'], $data['shop_id'], $data['boss_id']);
        $BusMemberBeautycard->setAttributes($data);

        if (empty($BusMemberBeautycard->card_name)) {
            $this->errorMessage = '卡名称不能为空';
            return false;
        }
        if ($BusMemberBeautycard->total_times < $BusMemberBeautycard->remain_times) {
            $this->errorMessage = '使用次数不能大于总次数';
            return false;
        }

        return $BusMemberBeautycard->update(false);
    }
    
    /**
     * 记录会员余额记录
     * @date: 2016-3-16 
     * @author: futao
     */
    public function memberBalancelog($memberId,$data)
    {
    	$memberInfo = $this->findOne($memberId);
    		$accountModel = new BusAccount();
    		if($data['type']=='储值卡'){
	    		$accountModel->consume_type = '储值卡';
	    		$accountModel->account_type = $data['account_type'];
	    		$accountModel->account_time = date('Y-m-d H:i:s');
	    		$accountModel->account_money = $data['account_money'];
	    		$accountModel->member_id = $memberId;
	    		$accountModel->shop_id = $memberInfo->shop_id;
	    		$accountModel->change_balance_money = $data['member_balance'];
	    		$accountModel->save(false);
    		}elseif($data['type']=='赠送金'){
	    		$accountModel->consume_type = '赠送金';
	    		$accountModel->account_type = $data['account_type'];
	    		$accountModel->account_time = date('Y-m-d H:i:s');
	    		$accountModel->account_money = $data['account_money'];
	    		$accountModel->member_id = $memberId;
	    		$accountModel->shop_id = $memberInfo->shop_id;
	    		$accountModel->change_give_balance_money = $data['member_give_balance'];
	    		$accountModel->save(false);
    		}elseif($data['type']=='欠款'){
	    		$accountModel->consume_type = '欠款';
	    		$accountModel->account_type = $data['account_type'];
	    		$accountModel->account_time = date('Y-m-d H:i:s');
	    		$accountModel->account_money = $data['account_money'];
	    		$accountModel->member_id = $memberId;
	    		$accountModel->shop_id = $memberInfo->shop_id;
	    		$accountModel->change_debt_money = $data['member_debt'];
	    		$accountModel->save(false);
    		}
    	}
    /**
     * 获取收入支出类型和金额
     * @date: 2016-3-17 
     * @author: futao
     */
	public function getType($beforMoney,$afterMoney)
	{
		if($beforMoney > $afterMoney){
			$money = $beforMoney - $afterMoney;
			return (object)['money'=>$money,'type'=>2];
		}else{
			$money = $afterMoney - $beforMoney;
			return (object)['money'=>$money,'type'=>1];
		}
	}

    /**
     * 今日过生的会员
     * @param int $shop_id 分店id
     * @return int|string
     */
    public static function birthday($shop_id)
    {
        $date = date('m-d');
        return self::find()->where(['shop_id' => $shop_id])->andWhere(['like', 'member_birthday', "{$date}"])->count();
    }
}
